package com;

import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author wdl
 */
@WebServlet(name = "LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //charset=utf-8使得可以显示中文
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();

        //从客户端获取数据
        String account = request.getParameter("account");
        String password = request.getParameter("password");

        //创建实体类
        System.out.println("接收到：账号 " + account + "密码 " + password);

        //获得数据库操作对象
        CarDB cardb = new CarDB();
        //查找账号的密码是否正确
        int result = cardb.checkAccountAndPassword(account, password);
        //结果返回客户端
        JSONObject object = new JSONObject();
        object.put("result", result);
        //如果账号存在并密码正确
        if (result == 1) {
            //获取整个对象
            User user = cardb.queryDataByAccount(account);
            //封装好对象
            JSONObject data = new JSONObject();
            data.put("imageName", user.getImageName());
            data.put("account", user.getAccount());
            data.put("password", user.getPassword());
            data.put("name", user.getName());
            data.put("gender", user.getGender());
            data.put("tel", user.getTel());
            data.put("manager", user.getManager());
            object.put("data", data);
        }

        out.print(object);

        out.flush();
        out.close();
    }
}
